import React, { useState } from 'react';
import { useIntl, FormattedMessage } from 'umi';
import { Select, Button, Modal, Space } from 'antd';
import { getKernelVersionList } from '../service';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { ProForm, ModalForm, ProFormText, ProFormTextArea, ProFormSelect } from '@ant-design/pro-form';
import './searchinput.less'
let timeout;
let currentValue;
const fetch = (value, callback) => {
    if (timeout) {
      clearTimeout(timeout);
      timeout = null;
    }
    currentValue = value;
    const fake = async () => {
        const res = await getKernelVersionList().then((res) => {
            if (currentValue === value) {
                const resdata = res.data;
                const dataList = [];
                resdata.forEach(items => {
                    dataList.push(items.kernel_version);
                });
                const data = dataList.map((item) => ({
                    value: item,
                    text: item,
                }))
                callback(data);
            }
        }).catch((error) => {
            console.log(error);
        })
    }
    if (value) {
        timeout = setTimeout(fake, 100);
    } else {
        callback([]);
    }
};
const SearchInput = (props) => {
    const intl = useIntl();
    const [data, setData] = useState([]);
    const [value, setValue] = useState();
    const handleSearch = (newValue) => {
        fetch(newValue, setData);
    };
    const handleChange = (newValue) => {
        setValue(newValue);
    };

    return (
        <Select
        showSearch
        value={value}
        placeholder={props.placeholder}
        style={props.style}
        defaultActiveFirstOption={false}
        showArrow={false}
        filterOption={(input, option) => (option?.label ?? '').includes(input)}
        filterSort={(optionA, optionB) =>
            (optionA?.label ?? '').toLowerCase().localeCompare((optionB?.label ?? '').toLowerCase())
        }
        onSearch={handleSearch}
        onChange={handleChange}
        notFoundContent={
            (data.length > 0) ?
            <>
                <span>{intl.formatMessage({
                    id:'pages.hotfix.search_kernelversion_not_exist',
                    defaultMessage: 'The kernel you search is not exist!'
                })}</span>
                <a href={"/hotfix/version/customize/"}>{intl.formatMessage({id:'pages.hotfix.add_kernelversion', defaultMessage:'Add kernel version'})}</a>
            </> :
            <><span>{intl.formatMessage({
                id: 'pages.hotfix.search_kernelversion',
                defaultMessage: 'Please search your kernel!'
              })}</span></>
        }
        options={(data || []).map((d) => 
            ({
                value: d.value,
                label: d.text,
            })
        )}
        />
    );
};

export default SearchInput;